<template>
  <my-container>
    <!--查询-->
    <template #header>
      <el-form class="ad-form-query" :inline="true" :model="filter" @submit.native.prevent>

        <el-form-item>
          <el-select v-model="filter.xbcTypeId" clearable filterable placeholder="请选择物料类型" style="width:100%;">
            <el-option
              v-for="item in xbcTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-input
            v-model="filter.name"
            placeholder="物料号"
            clearable
            @keyup.enter.native="getXbcmaterrials"
          >
            <template #prefix>
              <i class="el-input__icon el-icon-search" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:getpage'])">
          <el-button icon="el-icon-search" type="primary" @click="getXbcmaterrials">查询</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:add'])">
          <el-button icon="el-icon-plus" type="primary" @click="onAdd">新增</el-button>
        </el-form-item>
        <el-form-item v-if="checkPermission(['api:warehouse:xbcmaterrial:batchsoftdelete'])">
          <my-confirm-button
            :disabled="sels.length === 0"
            :type="'delete'"
            :placement="'bottom-end'"
            :loading="deleteLoading"
            :validate="batchDeleteValidate"
            style="margin-left: 0px;"
            @click="onBatchDelete"
          >
            <template #content>
              <p>确定要批量删除吗？</p>
            </template>
            批量删除
          </my-confirm-button>
        </el-form-item>
      </el-form>
    </template>

    <vxe-grid
      ref="xGrid"
      border
      resizable
      stripe
      auto-resize
      show-overflow
      size="small"
      height="auto"
      :loading="listLoading"
      :seq-config="{startIndex: (tablePage.currentPage - 1) * tablePage.pageSize}"
      :pager-config="tablePage"
      :columns="tableColumn"
      :data="roles"
      @page-change="pageChange"
    >
      <template v-if="checkPermission(['api:warehouse:xbcmaterrial:update','api:warehouse:xbcmaterrial:softdelete'])" v-slot:operate="{$index, row }">
        <vxe-button v-if="checkPermission(['api:warehouse:xbcmaterrial:update'])" icon="fa fa-edit" title="编辑" circle @click="onEdit($index,row)" />
        <vxe-button v-if="checkPermission(['api:warehouse:xbcmaterrial:softdelete'])" icon="fa fa-trash" title="删除" circle @click="onDelete($index,row)" />
      </template>
    </vxe-grid>

    <vxe-modal v-if="checkPermission(['api:warehouse:xbcmaterrial:add'])" v-model="modalShow" :loading="submitLoading" title="新增物料" width="600" height="480" destroy-on-close resize>
      <vxe-form :data="addForm" :rules="addFormRules" title-align="right" title-width="120" @submit="onAddSubmit">
        <!-- <vxe-form-item title="基本信息" span="24" title-align="left" title-width="200px" :title-prefix="{icon: 'fa fa-address-card-o'}" /> -->
        <vxe-form-item title="物料分类" field="xbcTypeId" span="12" :item-render="{name: 'ElSelect', options: xbcTypeList, events: { change: changeValue }}" />
        <vxe-form-item title="物料号" field="code" span="12" :item-render="{name: 'ElInput', attrs: {placeholder: '请输入物料号'}}" />
        <vxe-form-item title="物料名称" field="name" span="12" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入物料名称'}}" />
        <vxe-form-item title="库存单位" field="ckdwId" span="12" :item-render="{name: 'ElSelect', options: ckdwList,props: { clearable: true, filterable: true }}" />
        <vxe-form-item title="最小发放单位" field="zxffdwId" span="12" :item-render="{name: 'ElSelect', options: wlffdwList,props: { clearable: true, filterable: true }}" />
        <vxe-form-item title="最小发放数量" field="zxffslId" span="12" :item-render="{name: 'ElSelect', options: wlffslList,props: { clearable: true, filterable: true }}" />
        <vxe-form-item title="客户代码" field="khdmId" span="12" :item-render="{name: 'ElSelect', options: khdmList,props: { clearable: true, filterable: true }}" />
        <vxe-form-item title="默认库位" field="xbcLocationId" span="12" :item-render="{name: 'ElSelect', options: xbcLocationList,props: { filterable: true }}" />
        <vxe-form-item title="生命周期" field="lifeTime" span="12" :item-render="{name: 'ElInputNumber'}" />
        <vxe-form-item title="启用" field="enabled" span="12" :item-render="{name: 'ElSwitch'}" />
        <vxe-form-item title="物料规格" field="wlgg" span="24" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入物料规格'}}" />
        <vxe-form-item title="备注" field="remark" span="24" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入备注'}}" />
        <vxe-form-item align="right" span="24">
          <vxe-button type="reset">重置</vxe-button>
          <vxe-button type="submit" status="primary">提交</vxe-button>
        </vxe-form-item>

      </vxe-form>
    </vxe-modal>

    <vxe-modal v-if="checkPermission(['api:warehouse:xbcmaterrial:update'])" v-model="editFormVisible" :loading="submitLoading" title="编辑物料" width="600" height="480" destroy-on-close resize>
      <vxe-form ref="editForm" :data="editForm" :rules="editFormRules" title-align="right" title-width="120" @submit="onEditSubmit">
        <!-- <vxe-form-item title="基本信息" span="24" title-align="left" title-width="200px" :title-prefix="{icon: 'fa fa-address-card-o'}" /> -->
        <vxe-form-item title="物料分类" field="xbcTypeId" span="12" :item-render="{name: 'ElSelect', props:{ disabled: editForm.canChangeType}, options: xbcTypeList, events: { change: changeValue }}" />
        <vxe-form-item title="物料号" field="code" span="12" :item-render="{name: 'ElInput', attrs: {placeholder: '请输入物料号'}}" />
        <vxe-form-item title="物料名称" field="name" span="12" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入物料名称'}}" />
        <vxe-form-item title="库存单位" field="ckdwId" span="12" :item-render="{name: 'ElSelect', options: ckdwList}" />
        <vxe-form-item title="最小发放单位" field="zxffdwId" span="12" :item-render="{name: 'ElSelect', options: wlffdwList}" />
        <vxe-form-item title="最小发放数量" field="zxffslId" span="12" :item-render="{name: 'ElSelect', options: wlffslList}" />
        <vxe-form-item title="客户代码" field="khdmId" span="12" :item-render="{name: 'ElSelect', options: khdmList}" />
        <vxe-form-item title="默认库位" field="xbcLocationId" span="12" :item-render="{name: 'ElSelect', options: xbcLocationList}" />
        <vxe-form-item title="生命周期" field="lifeTime" span="12" :item-render="{name: 'ElInputNumber'}" />
        <vxe-form-item title="启用" field="enabled" span="12" :item-render="{name: 'ElSwitch'}" />
        <vxe-form-item title="物料规格" field="wlgg" span="24" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入物料规格'}}" />
        <vxe-form-item title="备注" field="remark" span="24" :item-render="{name: 'ElInput',attrs: {placeholder: '请输入备注'}}" />
        <vxe-form-item align="right" span="24">
          <vxe-button type="cancel" @click="editclose()">取消</vxe-button>
          <vxe-button type="submit" status="primary">提交</vxe-button>
        </vxe-form-item>
      </vxe-form>
    </vxe-modal>

  </my-container>
</template>

<script>
import XEUtils from 'xe-utils'
import { getxbcTypeList } from '@/api/warehouse/xbctype'
// import { removeXbcWarehouse, batchRemoveXbcWarehouse } from '@/api/warehouse/xbcwarehouse'
import { getxbcLocationList } from '@/api/warehouse/xbclocation'
import { getWlffdwList } from '@/api/admin/dictionary'
import { getXbcmaterrialListPage, addMaterrial, editXbcmaterrial, getMaterrial, removeXbcmaterrial, batchRemoveXbcmaterrial } from '@/api/warehouse/xbcmaterrial'

import MyContainer from '@/components/my-container'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  name: 'Roles',
  components: { MyContainer, MyConfirmButton },
  data() {
    return {
      filter: {
        name: '',
        xbcTypeId: null // 物料类别
      },
      cvisible: false,
      submitLoading: false,
      modalShow: false,
      roles: [],
      statusList: [
        { name: '激活', value: true },
        { name: '禁用', value: false }
      ],
      xbcTypeList: [], // 物料分类下拉
      xbcLocationList: [], // 库位下拉
      wlffdwList: [], // 物料最小发放单位
      wlffslList: [], // 物料最小发放数量
      khdmList: [], // 客户代码
      ckdwList: [], // 库存单位列表
      tableColumn: [
        { type: 'checkbox', width: 50 },
        { type: 'seq', width: 60 },
        { field: 'code', title: '物料号' },
        { field: 'name', title: '物料名称' },
        { field: 'wlgg', title: '物料规格' },
        { field: 'ckdwName', title: '库存单位' },
        { field: 'lifeTime', title: '生命周期' },
        { field: 'typeName', title: '分类' },
        { field: 'locationName', title: '默认库位' },
        { field: 'khDm', title: '客户代码' },
        { field: 'zxffdwName', title: '最小发放单位' },
        { field: 'zxffslName', title: '最小发放数量' },
        { field: 'enabled', title: '状态', cellRender: { name: 'ElSwitch', props: { disabled: true }}},
        { field: 'createdTime', title: '操作时间', formatter: this.formatDate },
        { field: 'remark', title: '备注' }
      ],
      tablePage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      pager: {},
      listLoading: false,
      sels: [], // 列表选中列

      addDialogFormVisible: false,
      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      editFormRules: {
        code: [{ required: true, message: '请输入物料号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        enabled: [{ required: true, message: '请选择状态', trigger: 'change' }],
        lifeTime: [{ required: true, message: '请填写生命周期', trigger: 'blur' }],
        xbcTypeId: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
        // zxffdwId: [{ required: true, message: '请选择最小发放单位', trigger: 'change' }],
        // zxffslId: [{ required: true, message: '请选择最小发放数量', trigger: 'change' }],
        // khdmId: [{ required: true, message: '请选择客户代码', trigger: 'change' }],
        xbcLocationId: [{ required: true, message: '请选择库位', trigger: 'change' }]
      },
      // 编辑界面数据
      editForm: {
        id: 0,
        code: '',
        name: '',
        remark: '',
        xbcTypeId: '', // 物料类别
        xbcLocationId: '', // 库位id
        wlgg: '', // 物料规格
        khdmId: null, // 客户代码
        ckdwId: null, // 库存单位
        zxffslId: null, // 最小发放数量
        zxffdwId: null, // 最小发放单位
        lifeTime: 0, // 生命周期
        enabled: '',
        canChangeType: true
      },
      editFormRef: null,

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        code: [{ required: true, message: '请输入物料号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        enabled: [{ required: true, message: '请选择状态', trigger: 'change' }],
        lifeTime: [{ required: true, message: '请填写生命周期', trigger: 'blur' }],
        xbcTypeId: [{ required: true, message: '请选择物料分类', trigger: 'change' }],
        // zxffdwId: [{ required: true, message: '请选择最小发放单位', trigger: 'change' }],{ validator: isInteger, trigger: 'blur' }
        // zxffslId: [{ required: true, message: '请选择最小发放数量', trigger: 'change' }],
        // khdmId: [{ required: true, message: '请选择客户代码', trigger: 'change' }],
        xbcLocationId: [{ required: true, message: '请选择库位', trigger: 'change' }]
      },
      // 新增界面数据
      addForm: {
        code: '',
        name: '',
        remark: '',
        xbcTypeId: null, // 物料类别
        xbcLocationId: null, // 库位id
        wlgg: '', // 物料规格
        khdmId: null, // 客户代码
        ckdwId: null, // 库存单位
        zxffslId: null, // 最小发放数量
        zxffdwId: null, // 最小发放单位
        lifeTime: 0, // 生命周期
        enabled: true
      },
      addFormRef: null,
      deleteLoading: false
    }
  },
  mounted() {
    if (this.checkPermission(['api:warehouse:xbcmaterrial:update', 'api:warehouse:xbcmaterrial:softdelete'])) {
      this.tableColumn.push({ title: '操作', width: 100, slots: { default: 'operate' }})
    }
    this.getxbcTypeList()
    this.getXbcmaterrials()
  },
  methods: {
    formatDate({ cellValue }) {
      return XEUtils.toDateString(cellValue, 'yyyy-MM-dd')
    },
    async pageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.getXbcmaterrials()
    },
    // 获取物料列表
    async getXbcmaterrials() {
      const para = {
        currentPage: this.tablePage.currentPage,
        pageSize: this.tablePage.pageSize,
        filter: this.filter
      }

      this.listLoading = true
      const res = await getXbcmaterrialListPage(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }

      this.tablePage.total = res.data.total
      const data = res.data.list
      data.forEach(d => {
        d._loading = false
      })
      this.roles = data
    },

    async getxbcTypeList() {
      const res = await getxbcTypeList()
      if (res && res.success) {
        this.xbcTypeList = res.data
      }
    },
    // 显示编辑界面
    async onEdit(index, row) {
      const loading = this.$loading()
      if (this.wlffdwList.length === 0) {
        await this.getWlffdwList('WL_ZXFFDW')
      }
      if (this.wlffslList.length === 0) {
        await this.getWlffdwList('WL_ZXFFSL')
      }
      if (this.khdmList.length === 0) {
        await this.getWlffdwList('KH_DM')
      }
      if (this.ckdwList.length === 0) {
        await this.getWlffdwList('WL_RKDW')
      }
      if (this.xbcTypeList.length === 0) {
        await this.getxbcTypeList()
      }
      // if (this.xbcTypeList.length === 0) {
      //   await this.getxbcTypeList()
      // }
      const res = await getMaterrial({ id: row.id })
      loading.close()
      if (res && res.success) {
        const data = res.data
        this.editForm = data
        this.editGetxbcLocationList(this.editForm.xbcTypeId)
        this.editFormVisible = true
      }
    },
    closeEditForm() {
    },
    // 显示新增界面
    async onAdd() {
      const loading = this.$loading()
      // this.modalShow = !this.modalShow
      if (this.wlffdwList.length === 0) {
        await this.getWlffdwList('WL_ZXFFDW')
      }
      if (this.wlffslList.length === 0) {
        await this.getWlffdwList('WL_ZXFFSL')
      }
      if (this.khdmList.length === 0) {
        await this.getWlffdwList('KH_DM')
      }
      if (this.ckdwList.length === 0) {
        await this.getWlffdwList('WL_RKDW')
      }
      loading.close()
      this.modalShow = !this.modalShow
      // this.addFormVisible = true
    },
    closeAddForm() {
    },
    // 编辑验证
    editFormValidate: function() {
      let isValid = false
      this.$refs.editForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    // 编辑
    async onEditSubmit() {
      this.submitLoading = true
      const para = _.cloneDeep(this.editForm)
      const res = await editXbcmaterrial(para)
      this.submitLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.updateOk'),
        type: 'success'
      })
      // this.$refs['editForm'].resetFields()
      this.editFormVisible = false
      this.getXbcmaterrials()
    },
    // 新增验证
    addFormValidate: function() {
      let isValid = false
      this.$refs.addForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },

    async changeValue() {
      if (this.modalShow === true) {
        this.getxbcLocationList(this.addForm.xbcTypeId)
      } else if (this.editFormVisible === true) {
        this.getxbcLocationList(this.editForm.xbcTypeId)
      }
    },
    editclose() {
      this.editFormVisible = false
    },
    async getxbcLocationList(id) {
      const res = await getxbcLocationList({ id: id })
      if (res && res.success) {
        this.xbcLocationList = res.data
        this.addForm.xbcLocationId = null
        this.editForm.xbcLocationId = null
      }
    },

    async getWlffdwList(id) {
      const res = await getWlffdwList({ dicCode: id })
      if (res && res.success) {
        if (id === 'WL_ZXFFDW') {
          this.wlffdwList = res.data
        }
        if (id === 'WL_ZXFFSL') {
          this.wlffslList = res.data
        }
        if (id === 'KH_DM') {
          this.khdmList = res.data
        }
        if (id === 'WL_RKDW') {
          this.ckdwList = res.data
        }
      }
    },
    async editGetxbcLocationList(id) {
      const res = await getxbcLocationList({ id: id })
      if (res && res.success) {
        this.xbcLocationList = res.data
      }
    },
    // 新增
    async onAddSubmit() {
      this.submitLoading = true
      const para = _.cloneDeep(this.addForm)

      const res = await addMaterrial(para)
      this.submitLoading = false

      if (!res?.success) {
        return
      }

      this.$message({
        message: this.$t('admin.addOk'),
        type: 'success'
      })
      this.modalShow = !this.modalShow
      this.getXbcmaterrials()
    },
    // 删除验证
    deleteValidate(row) {
      let isValid = true
      if (row && row.name === 'admin') {
        this.$message({
          message: row.description + '，禁止删除！',
          type: 'warning'
        })
        isValid = false
      }

      return isValid
    },
    // 删除
    async onDelete(index, row) {
      this.$XModal.confirm('您确定要删除该数据?').then(async(type) => {
        if (type === 'confirm') {
          row._loading = true
          const para = { id: row.id }
          const res = await removeXbcmaterrial(para)
          row._loading = false

          if (!res?.success) {
            return
          }
          this.$message({
            message: this.$t('admin.deleteOk'),
            type: 'success'
          })
          this.getXbcmaterrials()
        }
      })
    },
    // 批量删除验证
    batchDeleteValidate() {
      let isValid = true
      var row = this.sels && this.sels.find(s => s.name === 'admin')
      if (row && row.name === 'admin') {
        this.$message({
          message: row.description + '，禁止删除！',
          type: 'warning'
        })
        isValid = false
      }

      return isValid
    },
    // 批量删除
    async onBatchDelete() {
      const para = { ids: [] }
      para.ids = this.sels.map(s => {
        return s.id
      })

      this.deleteLoading = true
      const res = await batchRemoveXbcmaterrial(para.ids)
      this.deleteLoading = false

      if (!res?.success) {
        return
      }
      this.$message({
        message: this.$t('admin.batchDeleteOk'),
        type: 'success'
      })

      this.getXbcmaterrials()
    },
    selsChange: function(sels) {
      this.sels = sels
    }
  }
}
</script>
